package com.hgy.fxui.dao;

import com.hgy.fxui.model.PurchaseOrder;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Map;

@Mapper
public interface PurchaseOrderDao {
    /**
     * 获取近几个月的采购金额统计
     */
    @Select("SELECT DATE_FORMAT(operation_time, '%Y-%m') as month, " +
            "SUM(quantity * unit_price) as amount " +
            "FROM purchase_order " +
            "WHERE operation_time >= DATE_SUB(CURDATE(), INTERVAL #{months} MONTH) " +
            "GROUP BY DATE_FORMAT(operation_time, '%Y-%m') " +
            "ORDER BY month")
    List<Map<String, Object>> getMonthlyPurchaseAmount(int months);

    /**
     * 获取今日采购订单数
     */
    @Select("SELECT COUNT(*) FROM purchase_order WHERE DATE(operation_time) = CURDATE()")
    int getTodayOrdersCount();

    /**
     * 获取今日采购总金额
     */
    @Select("SELECT COALESCE(SUM(quantity * unit_price), 0) " +
            "FROM purchase_order " +
            "WHERE DATE(operation_time) = CURDATE()")
    Double getTodayPurchaseAmount();

    /**
     * 获取本月采购总金额
     */
    @Select("SELECT COALESCE(SUM(quantity * unit_price), 0) " +
            "FROM purchase_order " +
            "WHERE YEAR(operation_time) = YEAR(CURDATE()) " +
            "AND MONTH(operation_time) = MONTH(CURDATE())")
    Double getCurrentMonthPurchaseAmount();

    @Select("SELECT MONTH(operation_time) as month, SUM(quantity) as amount " +
            "FROM purchase_order " +
            "WHERE operation_time >= DATE_SUB(NOW(), INTERVAL 6 MONTH) " +
            "GROUP BY MONTH(operation_time) " +
            "ORDER BY month DESC")
    List<Map<String, Object>> getMonthlyPurchaseStats();

    @Select("SELECT p.*, s.name AS supplierName, d.name AS drugName, d.specification AS drugSpec FROM purchase_order p " +
            "JOIN drug d ON p.drug_id = d.id " +
            "JOIN supplier s ON p.supplier_id = s.id " +
            "ORDER BY operation_time DESC")
    List<PurchaseOrder> getAllPurchaseOrders();

    @Insert("INSERT INTO purchase_order (supplier_id, drug_id, order_type, quantity, unit_price, operator, operation_time, note) " +
            "VALUES (#{supplierId}, #{drugId}, #{orderType}, #{quantity}, #{unitPrice}, #{operator}, #{operationTime}, #{note})")
    int insert(PurchaseOrder order);
}
